<template>
  <div class="crawler-article-list">
    <div class="header">
      <el-button-group>
        <el-button type="primary" @click="showCrawlerDialog">自定义爬虫任务</el-button>
      </el-button-group>
    </div>

    <!-- 爬虫任务状态 tab -->
    <el-table :data="crawlerTask.activeTasks" v-loading="crawlerTask.loading">
      <el-table-column prop="name" label="任务名称" width="120" />
      <el-table-column prop="taskId" label="任务ID" width="280" />
      <el-table-column prop="ruleDescription" label="任务描述" width="180" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getTaskStatusType(row.status)">
            {{ getTaskStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="pageCount" label="已爬取页数" width="100" />
      <el-table-column prop="startTime" label="开始时间" width="180" />
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button
              type="danger"
              link
              @click="handleStopTask(row)"
              v-if="row.canStop"
          >
            停止
          </el-button>
          <el-button
              type="success"
              link
              @click="handleDeleteTask(row)"
              v-if="row.canDelete"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        v-model:current-page="crawlerTask.currentPage"
        v-model:page-size="crawlerTask.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :layout="'sizes, prev, pager, next, jumper, total'"
        :total="crawlerTask.total"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
    />

    <!-- 爬虫任务配置弹窗 -->
    <el-dialog v-model="crawlerVisible" title="新建爬虫任务" width="600px">
      <el-form :model="crawlerTask.crawlerForm" label-width="120px" :rules="rules" ref="crawlerFormRef">
        <el-form-item label="任务名称" prop="name">
          <el-input v-model="crawlerTask.crawlerForm.name" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="爬取规则" prop="ruleId">
          <el-select
              v-model="crawlerTask.crawlerForm.ruleId"
              @change="handleRuleChange"
              placeholder="请选择规则"
          >
            <el-option
                v-for="rule in crawlerTask.crawlerRules"
                :key="rule.id"
                :label="rule.name"
                :value="rule.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="规则描述" prop="ruleDescription">
          <el-input v-model="crawlerTask.crawlerForm.ruleDescription" placeholder="自动填充规则描述" disabled />
        </el-form-item>
        <el-form-item label="自动发布">
          <el-switch v-model="crawlerTask.crawlerForm.autoPublish" />
        </el-form-item>
        <el-form-item label="爬取图片">
          <el-switch v-model="crawlerTask.crawlerForm.crawlImages" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="crawlerVisible = false">取消</el-button>
        <el-button type="primary" @click="startCrawler">开始爬取</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useTaskStore } from '@/stores/crawlerTask.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useWebSocket } from '@/stores/crawlerWebSocket.js'

const crawlerTask = useTaskStore()
const { connectWebSocket, subscribeToTask, closeWebSocket, subscribeToActiveTasks, ws } = useWebSocket(crawlerTask)

const crawlerFormRef = ref()
// 弹窗控制
const crawlerVisible = ref(false)

const handleRuleChange = (ruleId) => {
  // 根据选中的 ruleId 找到对应的描述
  const selectedRule = crawlerTask.crawlerRules.find(rule => rule.id === ruleId);
  if (selectedRule) {
    crawlerTask.crawlerForm.ruleDescription = selectedRule.description;
  } else {
    crawlerTask.crawlerForm.ruleDescription = ''; // 如果未匹配则清空描述
  }
}

const showCrawlerDialog = async () => {
  await crawlerTask.fetchCrawlerRules()
  crawlerVisible.value = true
}

// 分页处理
const handlePageChange = () => {
  crawlerTask.fetchCrawlerList()
}

const handleSizeChange = (val) => {
  crawlerTask.pageSize = val;
  crawlerTask.fetchCrawlerList()
};

// 启动爬虫任务
const startCrawler = async () => {
  try {
    await crawlerFormRef.value.validate()
    await crawlerTask.createCrawlerTask()
    ElMessage.success('爬虫任务已启动')
    crawlerVisible.value = false
    crawlerTask.resetForm()
    await getActiveTasks()
    // 订阅新创建的任务
    subscribeToTask(crawlerTask.taskId)
  } catch (error) {
    ElMessage.error(error.message || '启动任务失败')
  }
}

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入任务名称', trigger: 'blur' }
  ],
  ruleId: [
    { required: true, message: '请选择爬取规则', trigger: 'change' }
  ]
}

// 获取活跃任务列表
const getActiveTasks = async () => {
  try {
    await crawlerTask.fetchCrawlerList()
    if (ws.value?.readyState === WebSocket.OPEN) {
      subscribeToActiveTasks()
    }
  } catch (error) {
    ElMessage.error('获取任务列表失败')
  }
}

// 处理任务状态显示
const getTaskStatusType = (status) => {
  const statusMap = {
    'RUNNING': 'primary',
    'STOPPED': 'success',
    'ERROR': 'danger',
    'INIT': 'info',
  }
  return statusMap[status] || 'info'
}

const getTaskStatusText = (status) => {
  const statusMap = {
    'RUNNING': '运行中',
    'STOPPED': '已停止',
    'ERROR': '出错',
    "INIT": '初始化中'
  }
  return statusMap[status] || '未知状态'
}

// 停止任务
const handleStopTask = async (row) => {
  try {
    await ElMessageBox.confirm('确认停止该爬虫任务?')
    await crawlerTask.stopCrawlerTask(row.taskId)
    ElMessage.success('任务已停止')
    await getActiveTasks()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('停止任务失败')
    }
  }
}

// 停止任务
const handleDeleteTask = async (row) => {
  try {
    await ElMessageBox.confirm('确认删除该爬虫任务?')
    await crawlerTask.deleteCrawlerTasks(row.taskId)
    ElMessage.success('任务已删除')
    await getActiveTasks()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除任务失败')
    }
  }
}

onMounted(async () => {
  await getActiveTasks()
  // 然后建立WebSocket连接
  connectWebSocket()
})

onUnmounted(() => {
  closeWebSocket()
})
</script>

<style scoped>
.crawler-article-list {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

@keyframes blink {
  50% { opacity: 0.5; }
}

</style>